package com.fjnu.service;

import com.fjnu.annotation.ExceptionGlobalCatch;
import com.fjnu.dao.UserDao;
import com.fjnu.dto.PageResult;
import com.fjnu.dto.UserConditionDto;
import com.fjnu.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@ExceptionGlobalCatch
public class UserService {

    @Autowired
    private UserDao userDao;

    /**
     * 根据用户名查询用户
     */
    public User queryByName(String username) {
        if (username == null || username.trim().isEmpty()) {
            return null;
        }
        return userDao.selectByUsername(username);
    }

    /**
     * 用户注册
     */
    @Transactional
    public int register(User user) {
        if (user == null || user.getUsername() == null || user.getPassword() == null) {
            return 0;
        }
        // 检查用户名是否已存在
        User existUser = userDao.selectByUsername(user.getUsername());
        if (existUser != null) {
            return 0;
        }
        // 执行注册
        return userDao.insert(user);
    }

    /**
     * 修改用户密码
     */
    @Transactional
    public int changePassword(String userId, String newPassword) {
        if (userId == null || newPassword == null) {
            return 0;
        }
        try {
            Integer id = Integer.parseInt(userId);
            return userDao.updatePassword(id, newPassword);
        } catch (NumberFormatException e) {
            return 0;
        }
    }

    /**
     * 分页查询用户列表
     */
    public PageResult<User> queryUsers(UserConditionDto userCondition, Integer pageNum, Integer pageSize) {
        if (pageNum == null || pageSize == null || pageNum < 1 || pageSize < 1) {
            return new PageResult<>(0, 0, 0L, null);
        }
        int offset = (pageNum - 1) * pageSize;
        List<User> userList = userDao.selectByCondition(userCondition, offset, pageSize);
        Long total = userDao.countByCondition(userCondition);
        return new PageResult<>(pageNum, pageSize, total, userList);
    }

    /**
     * 为用户分配角色
     */
    @Transactional
    public void addAssignRole(String userId, List<Integer> roleIds) {
        if (userId == null || roleIds == null || roleIds.isEmpty()) {
            throw new IllegalArgumentException("用户ID和角色ID不能为空");
        }
        Integer uid;
        try {
            uid = Integer.parseInt(userId);
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("用户ID格式错误");
        }
        // 先删除旧角色关联
        userDao.deleteUserRoles(uid);
        // 新增新角色关联
        int successCount = userDao.batchInsertUserRoles(uid, roleIds);
        if (successCount != roleIds.size()) {
            throw new RuntimeException("角色分配失败");
        }
    }
}